package ltd.trackan.messagecenter.model.coommon;

import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONWriter;
import lombok.Data;

import java.io.Serializable;

/**
 * @author wxa
 */
@Data
public class RestBean<T> implements Serializable {
    private static final long serialVersionUID = 3550021498355364894L;
    private int code;
    private T data;
    private String msg;
    
    public RestBean() {
    }
    
    public RestBean(int code, T data, String msg) {
        this.code = code;
        this.data = data;
        this.msg = msg;
    }
    
    /* 自定义类型 */
    public static <T> RestBean<T> result(int statusCode, T data, String msg) {
        return new RestBean<>(statusCode, data, msg);
    }
    
    public static <T> RestBean<T> result(StatusCode statusCode, T data, String msg) {
        return result(statusCode.getCode(), data, msg);
    }
    
    public static <T> RestBean<T> result(StatusCode statusCode, T data) {
        return result(statusCode.getCode(), data, statusCode.getMsg());
    }
    
    public static RestBean<String> result(StatusCode statusCode, String msg) {
        return result(statusCode.getCode(), "", msg);
    }
    
    public static RestBean<String> result(StatusCode statusCode) {
        return result(statusCode.getCode(), "", statusCode.getMsg());
    }
    
    /* 成功的数据 */
    public static <T> RestBean<T> success(T data, String msg) {
        return result(StatusCode.SUCCESS, data, msg);
    }
    
    public static <T> RestBean<T> success(T data) {
        return success(data, StatusCode.SUCCESS.getMsg());
    }
    
    public static RestBean<String> success(String msg) {
        return success("", msg);
    }
    
    public static RestBean<String> success() {
        return success(StatusCode.SUCCESS.getMsg());
    }
    
    /* 失败的数据 */
    public static <T> RestBean<T> failure(T data, String msg) {
        return result(StatusCode.FAILURE, data, msg);
    }
    
    public static <T> RestBean<T> failure(T data) {
        return failure(data, StatusCode.FAILURE.getMsg());
    }
    
    public static RestBean<String> failure(String msg) {
        return failure("", msg);
    }
    
    public static RestBean<String> failure() {
        return failure(StatusCode.FAILURE.getMsg());
    }
    
    // 将当前对象转换为JSON格式的字符串用于返回
    public String asJsonString() {
        return JSONObject.toJSONString(this, JSONWriter.Feature.WriteNulls);
    }
}